package com.member.web.controller.shop;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.annotation.Log;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.BusinessType;
import com.member.common.enums.DeleteEnum;
import com.member.common.utils.DateUtils;
import com.member.common.utils.poi.ExcelUtil;
import com.member.shop.domain.*;
import com.member.shop.mapper.SysBizCouponMapper;
import com.member.shop.mapper.SysBizCouponReceiveMapper;
import com.member.shop.service.*;
import com.member.shop.vo.SysBizShopCertificationVo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 【店铺认证】控制器
 *
 * @author lixinchen
 * @version 1.0
 * @date 2025-01-10
 **/
@RestController
@RequestMapping("/shop/shopCertification")
public class SysBizShopCertificationController extends BaseController {
    @Resource
    private ISysBizShopCertificationService sysBizShopCertificationService;

    @Resource
    private ISysBizUserService sysBizUserService;

    @Resource
    private ISysBizTenantService sysBizTenantService;

    @Resource
    private ISysBizCouponGrantService sysBizCouponGrantService;

    @Resource
    private SysBizCouponMapper sysBizCouponMapper;

    private void setTenantId(SysBizShopCertification sysBizShopCertification) {
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            sysBizShopCertification.setTenantId(tenantId);
        }
    }

    /**
     * 查询店铺认证列表
     */
    @PreAuthorize("@ss.hasPermi('shop:shopCertification:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBizShopCertification sysBizShopCertification) {
        startPage();
        setTenantId(sysBizShopCertification);
        List<SysBizShopCertification> list = sysBizShopCertificationService.selectSysBizShopCertificationList(sysBizShopCertification);
        return getDataTable(list);
    }

    /**
     * 导出店铺认证列表
     */
    @PreAuthorize("@ss.hasPermi('shop:shopCertification:export')")
    @Log(title = "店铺认证", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBizShopCertification sysBizShopCertification) {
        List<SysBizShopCertificationVo> list = sysBizShopCertificationService.selectSysBizShopCertificationExport();
        ExcelUtil<SysBizShopCertificationVo> util = new ExcelUtil<SysBizShopCertificationVo>(SysBizShopCertificationVo.class);
        util.exportExcel(response, list, "店铺认证数据");
    }

    /**
     * 获取店铺认证详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:shopCertification:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysBizShopCertificationService.selectSysBizShopCertificationById(id));
    }

    /**
     * 新增店铺认证
     */
    @PreAuthorize("@ss.hasPermi('shop:shopCertification:add')")
    @Log(title = "店铺认证", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBizShopCertification sysBizShopCertification) {
        return toAjax(sysBizShopCertificationService.insertSysBizShopCertification(sysBizShopCertification));
    }

    /**
     * 修改店铺认证
     */
    @PreAuthorize("@ss.hasPermi('shop:shopCertification:edit')")
    @Log(title = "店铺认证", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBizShopCertification sysBizShopCertification) {
        if(sysBizShopCertification.getCertificationStatus()==3){
            SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(sysBizShopCertification.getUserId());
            sysBizUser.setSalesUserId(sysBizShopCertification.getSalesUserId());
            sysBizUserService.updateById(sysBizUser);
        }
        return toAjax(sysBizShopCertificationService.updateSysBizShopCertification(sysBizShopCertification));
    }


    @Resource
    private SysBizCouponReceiveMapper sysBizCouponReceiveMapper;

    @Resource
    private ISysBizTenantAreaService tenantAreaService;
    /**
     * 修改店铺认证状态
     */
    @PreAuthorize("@ss.hasPermi('shop:shopCertification:edit')")
    @Log(title = "店铺认证", businessType = BusinessType.UPDATE)
    @PutMapping("/editStatus")
    public AjaxResult editStatus(@RequestBody SysBizShopCertification sysBizShopCertification) {
        if(sysBizShopCertification.getCertificationStatus()==3){
            // 根据省市区获取站点ID
//            SysBizTenant bizTenant = sysBizTenantService.getOne(new LambdaQueryWrapper<SysBizTenant>()
//                    .eq(SysBizTenant::getProvince, sysBizShopCertification.getProvince())
//                    .apply("JSON_UNQUOTE(JSON_EXTRACT(city_area_json, '$[0].cityName')) = {0}", sysBizShopCertification.getCity())
//                    .apply("JSON_CONTAINS(city_area_json->'$[0].areas[*].areaName', JSON_QUOTE({0}))", sysBizShopCertification.getArea()));
//
            SysBizTenantArea bizTenant = tenantAreaService.getOne(new LambdaQueryWrapper<SysBizTenantArea>()
                    .eq(SysBizTenantArea::getProvince, sysBizShopCertification.getProvince())
                    .eq(SysBizTenantArea::getCity, sysBizShopCertification.getCity())
                    .eq(SysBizTenantArea::getArea, sysBizShopCertification.getArea())
                    .eq(SysBizTenantArea::getDeleted, DeleteEnum.NOT_DELETE.getKey())
            );

            if(bizTenant==null || !bizTenant.getTenantId().equals(sysBizShopCertification.getTenantId())){
                return AjaxResult.error("用户站点和地区不匹配");
            }
            sysBizShopCertification.setAuditTime(LocalDateTime.now());
            SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(sysBizShopCertification.getUserId());
            if(sysBizUser!=null){
                //如果用户站点ID和站点ID不匹配 重新分配了站点 则设置重新登录
                if(!sysBizUser.getTenantId().equals(bizTenant.getTenantId())){
                    sysBizUser.setReLogin(2);
                }

                sysBizUser.setSalesUserId(sysBizShopCertification.getSalesUserId());
                if(bizTenant != null){ // 如果查询出来对应的站点ID则更新 否则为默认站点ID
                    sysBizUser.setTenantId(bizTenant.getTenantId());
                }
                sysBizUserService.updateById(sysBizUser);
                sysBizShopCertification.setTenantId(sysBizUser.getTenantId());
            }else{
                return AjaxResult.error("用户不存在");
            }
            //查询该用户是否领取过新人优惠券
            try {
                SysBizCoupon sysBizCoupon = sysBizCouponMapper.selectOne(new LambdaQueryWrapper<SysBizCoupon>()
                        .eq(SysBizCoupon::getNewCoupon, 1)
                        .eq(SysBizCoupon::getTenantId, sysBizUser.getTenantId())
                        .eq(SysBizCoupon::getDeleted, DeleteEnum.NOT_DELETE.getKey()));

                if (sysBizCoupon != null) {
                    SysBizCouponGrant sysBizCouponGrant = new SysBizCouponGrant();
                    sysBizCouponGrant.setCouponId(sysBizCoupon.getId());
                    sysBizCouponGrant.setGrantNum(3L);
                    sysBizCouponGrant.setUserPhoneList(new ArrayList<String>() {{ add(sysBizUser.getUserPhone());}});
                    sysBizCouponGrantService.insertSysBizCouponGrant(sysBizCouponGrant);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());
            }


        }
        return toAjax(sysBizShopCertificationService.updateById(sysBizShopCertification));
    }


    /**
     * 删除店铺认证
     */
    @PreAuthorize("@ss.hasPermi('shop:shopCertification:remove')")
    @Log(title = "店铺认证", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(sysBizShopCertificationService.deleteSysBizShopCertificationById(id));
    }
}
